<?php

namespace app\api\controller\shop;

use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\Articletype;
use app\admin\model\City;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopdou;
use app\admin\model\Shopjoin;
use app\admin\model\Shopmeituan;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoptuan;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Userdoucode;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\MtUtil;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;

/**
 */
class Dou extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $appKey = "";
    protected $secret = "";

    public function _initialize()
    {
        parent::_initialize();
        $this->appKey = "awoh1q4tfg29z1yv";
        $this->secret = "b8976219b329b01d543e76a83c923720";
    }

    public function couponBuyList()
    {

        $page = $this->request->param('page');
        $startTime = $this->request->param('startTime');
        $endTime = $this->request->param('endTime');
        $mobile = $this->request->param('mobile');
        $where = array();


        $limit = 10;
        $offset = ($page - 1) * $limit;
        $shop_id = $this->request->param('shop_id');
        $userDouCodeModel = new Userdoucode();
        $where['Userdoucode.shop_id'] = $shop_id;
        $where['order.status'] = array("<>", 'paying');
        $shopOrderModel = new Shoporder();
        $amount = $shopOrderModel->where('status', 'not in', ['paying', 'refund'])->where('dou_code', "<>", '')->where('shop_id', $shop_id)->sum('amount');
        $refund = $shopOrderModel->where('status', 'refund')->where('shop_id', $shop_id)->where('dou_code', "<>", '')->sum('amount');


        $userModel = new \app\admin\model\User();
        $shopDouModel = new Shopdou();
        $list = $userDouCodeModel->where('shop_id', $shop_id)->limit($limit, $offset)->order('create_time', 'desc')->select();
        foreach ($list as $key => $val) {

            $user = $userModel->where('id', $val['user_id'])->find();
            $list[$key]['user'] = $user;
            $coupon = $shopDouModel->where('sku_id', $val['sku_id'])->where('shop_id', $shop_id)->find();
            $list[$key]['coupon'] = $coupon;

        }
        $ret = array();
        $ret['list'] = $list;
        $ret['total'] = $amount;
        $ret['refund'] = $refund;


        $this->success('', $ret);
    }


    public function getCouponList()
    {

        $shop_id = $this->request->param('shop_id');
        $shopDouModel = new Shopdou();
        $list = $shopDouModel->where('shop_id', $shop_id)->select();
        $this->success('', $list);
    }


    public function couponSet()
    {
        $id = $this->request->param('id');
        $hour = $this->request->param('hour');
        $room = $this->request->param('room');
        $start = $this->request->param('start');
        $end = $this->request->param('end');
        $week = $this->request->param('week');
        $room = json_decode(htmlspecialchars_decode($room), true);
        $week = json_decode(htmlspecialchars_decode($week), true);
        $type = $this->request->param('type');
        if (!$type) {
            $type = 'qp';
        }

        if ($hour == 0) {
            $this->error("时长不能设置为0");
        }

        $shopDouModel = new Shopdou();
        $newWeek = array();
        $w = "";
        foreach ($week as $key => $val) {
            $w .= $val['name'];
            if ($key != count($week) - 1) {
                $w .= ",";
            }
            if ($val['name'] == "一") {
                $newWeek[] = 1;
            }
            if ($val['name'] == "二") {
                $newWeek[] = 2;
            }
            if ($val['name'] == "三") {
                $newWeek[] = 3;
            }
            if ($val['name'] == "四") {
                $newWeek[] = 4;
            }
            if ($val['name'] == "五") {
                $newWeek[] = 5;
            }
            if ($val['name'] == "六") {
                $newWeek[] = 6;
            }
            if ($val['name'] == "日") {
                $newWeek[] = 7;
            }
        }

        $shopDouModel->where('id', $id)->update(['hour' => $hour, 'room_id' => json_encode($room), 'use_time' => $start . "~" . $end,
            'week' => json_encode($newWeek), 'type' => $type]);
        $this->success('成功');

    }


    public function syncCouponInfo()
    {


        $shop_id = $this->request->param('shop_id');
        $cursor = $this->request->param('cursor');
        $shopModel = new Shop();
        $shop = $shopModel->where('id', $shop_id)->find();
        $dou_id = $shop['dou_id'];

        if ($dou_id == '') $this->error("请联系客服，抖音暂未配置");

        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $this->appKey;
        $tokenReq["client_secret"] = $this->secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['data']['access_token'];


        $account_id = $dou_id;
        $url = "https://open.douyin.com/goodlife/v1/goods/product/online/query/?status=1&goods_creator_type=1&count=50&account_id=" . $account_id;

        if ($cursor != 0) {
            $url = "https://open.douyin.com/goodlife/v1/goods/product/online/query/?status=1&cursor=" . $cursor . "&goods_creator_type=1&count=50&account_id=" . $account_id;
        }

        error_log("===url==" . $url);
        $result = $this->http_curl_get($url, $token);


        $product = $result['data']['products'];
        $has_more = $result['data']['has_more'];
        $next_cursor = $result['data']['next_cursor'];
        if ($has_more == false) {
            $next_cursor = 0;
        }

        $poi_id = $shop['poi_id'];
        $shopDouModel = new Shopdou();
        $ret = array();
        foreach ($product as $key => $val) {

            $pois = $val['product']['pois'];
            $sku = $val['sku'];
            $skuId = $sku['sku_id'];
            $skuName = $sku['sku_name'];
            $isAdd = 0;
            foreach ($pois as $k => $v) {
                if ($v['poi_id'] == $poi_id && $skuName != '库存') {
                    $isAdd = 1;
                }
            }
            if ($isAdd == 1) {
                $db = array();
                $db['sku_id'] = $skuId;
                $db['sku_name'] = $skuName;
                $db['shop_id'] = $shop_id;
                $db['price'] = $sku['actual_amount'] / 100;
                $ret[] = $db;
                $skuDb = $shopDouModel->where('shop_id', $shop_id)->where('sku_id', $skuId)->find();
                if ($skuDb) {
                    $shopDouModel->where('id', $skuDb['id'])->update($db);
                } else {
                    $shopDouModel->insert($db);
                }
            } else {
                $shopDouModel->where('shop_id', $shop_id)->where('sku_id', $skuId)->delete();

            }
        }
        $list = $shopDouModel->where('shop_id', $shop_id)->select();

        $this->success($next_cursor, $list);
    }


    //post请求
    public function curl_post($url, $postdata)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); // 解决数据包大不能提交
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    //post请求
    public function curl_post2($url, $postdata, $token)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测

        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    public function http_curl_get($url, $token)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));

        $tmpInfo = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


}
